package com.hhz.lambda.part4;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * java8  内置的四大核心函数式接口
 * <p>
 * Consumer<T>:消费型接口
 * -------- void  accept(T t);
 * <p>
 * Supplier<T>:供给型接口
 * -------- T get();
 * <p>
 * Function<T>:函数型接口
 * -------- R apply(T t);
 * <p>
 * Predicate<T>:断言型接口
 * -------- boolean test(T t);
 * <p>
 * <p>
 * 其他类型函数式接口
 * BiFunction<T,R,U>             R apply(T t,R r);
 * <p>
 * UnaryOperator<T>              T apply(T t);
 * <p>
 * BinaryOperation<T>            T apply(T t);
 * <p>
 * BiConsumer<T,U>	             void accept(T t, U u);
 * <p>
 * 等等...
 *
 * @Author Rem
 * @Date 2020-02-11
 */

public class TestLambda4 {

    //1.Consumer<T>:消费型接口
    @Test
    public void test() {
        happy(100, con -> System.out.println("买玩具消费了" + con + "元"));
    }

    public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

    //2.Supplier<T>:供给型接口
    //需求：产生长度为5的10以内的随机数的集合
    @Test
    public void tes2() {
        List<Integer> list = produceNum(5, () -> new Random().nextInt(10));
        list.forEach(System.out::println);

    }

    public List<Integer> produceNum(int num, Supplier<Integer> sup) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }
        return list;
    }

    //3.Function<T>:函数型接口
    //需求：取出一个字符串的第二到第七的位置
    @Test
    public void tes3() {
        String sstr = strHander("Hello World", str -> str.substring(2, 7));
        System.out.println(sstr);
    }

    public String strHander(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    //4.Predicate<T>:断言型接口
    //需求：将满足条件的字符串放入集合中  字符串包含 p 的加到list中去
    @Test
    public void tes4() {
        List<String> strings = Arrays.asList("java", "c++", "pyhon", "php", "html");
        List<String> list = filterStr(strings, pre -> pre.contains("p"));
        List<String> list2 = filterStr2(strings, str -> str.contains("h"));
        list.forEach(System.out::println);
    }

    public List<String> filterStr(List<String> list, Predicate<String> pre) {
        List<String> strs = new ArrayList<>();
        for (String s : list) {
            if (pre.test(s)) {
                strs.add(s);
            }
        }
        return strs;
    }

    public List<String> filterStr2(List<String> list, Predicate<String> pre) {
        return list.stream().filter(str -> str.contains("p")).collect(Collectors.toList());
    }

}
